package com.roncoo.education.db.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.roncoo.education.api.request.RegistrationRequest;
import com.roncoo.education.db.dao.RegistrationDao;
import com.roncoo.education.db.entity.Registration;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RegistrationService {

    @Resource
    RegistrationDao registrationDao;


    public Registration getRegisById(Long id){
        return registrationDao.findById(id);
    }

    public PageInfo<Registration> getRegisPages(RegistrationRequest req){
        int pageNum = req.getPageNum();
        int pageSize = req.getCount();
        if (req.getPageNum() == null || req.getPageNum() <= 0 || req.getCount() == null) {
            pageNum = 1;
            pageSize = 20;
        }
        Registration query = new Registration();
        query.setRegName(req.getRegName());
        query.setRegPhone(req.getRegPhone());
        PageHelper.startPage(pageNum, pageSize);
        List<Registration> newsList = registrationDao.findByBean(query);
        return new PageInfo<>(newsList);
    }

    public Map<String,String> saveRegistra(RegistrationRequest req){
        Registration reg = BeanUtil.copyProperties(req,Registration.class);
        Map<String,String> ret = new HashMap<>();
        Registration query = new Registration();
        query.setRegName(req.getRegName());
        query.setRegPhone(req.getRegPhone());
        query.setRegCompany(req.getRegCompany());
        query.setRegEmail(req.getRegEmail());
        query.setRegPosition(req.getRegPosition());
        List<Registration> regisList = registrationDao.findByBean(query);
        if(CollectionUtil.isNotEmpty(regisList)){
            Registration regBean = regisList.get(0);
            ret.put("isError", "already exists");
            ret.put("id", String.valueOf(regBean.getId()));
            ret.put("code", "1");
            return ret;
        }

        reg.setRegTime(new Date());
        registrationDao.insert(reg);
        Long nid = reg.getId();

        ret.put("isError", "success");
        ret.put("id", String.valueOf(nid));
        ret.put("code", "1");
        return ret;
    }
}
